//
//  MessageListViewController.m
//  HDMainWindow
//
//  Created by apple on 2017/5/1.
//  Copyright © 2017年 com.devin.definesys. All rights reserved.
//

#import "ChatListViewController.h"

#import "ChatListMessageCell.h"
#import "ChatInputViewController.h"
#import "LLSearchControllerDelegate.h"
#import "LLSearchBar.h"
#import "LLUtils.h"
#import "UIKit+LLExt.h"
#import "LLSearchViewController.h"
#import "LLChatSearchController.h"

@interface ChatListViewController ()<UITableViewDelegate , UITableViewDataSource , UISearchBarDelegate, LLSearchControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;


@property (nonatomic) UIView *connectionAlertView;

@property (nonatomic) LLSearchBar *searchBar;

@property (nonatomic) UIView *tableHeaderView;

@end

@implementation ChatListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self ;
    self.tableView.dataSource = self ;
    
    _searchBar = [LLSearchBar defaultSearchBarWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SEARCH_TEXT_FIELD_HEIGHT + 16)];
    _searchBar.delegate = self;
    _searchBar.placeholder = @"搜索";
    
    _tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CGRectGetHeight(_searchBar.frame))];
    _tableHeaderView.backgroundColor = [UIColor clearColor];
    [_tableHeaderView addSubview:_searchBar];
    
    self.tableView.tableHeaderView = _tableHeaderView;
    
    NSInteger _viewHeight = SCREEN_HEIGHT;
    UIView *barView = [[UIView alloc] initWithFrame:CGRectMake(0,-_viewHeight, SCREEN_WIDTH, _viewHeight)];
    barView.backgroundColor = self.searchBar.barTintColor;
    [self.tableView addSubview:barView];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectionStateChanged:) name:LLConnectionStateDidChangedNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadCompleteHandler:) name:LLMessageUploadStatusChangedNotification object:nil];

}

- (UIView *)connectionAlertView {
    if (!_connectionAlertView) {
        _connectionAlertView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
        _connectionAlertView.backgroundColor = UIColorRGB(255, 223, 224);
        
        UIImageView *alertView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"connect_alert_error"]];
        alertView.frame = CGRectMake(20, (CGRectGetHeight(_connectionAlertView.frame) - 28)/2, 28, 28);
        [_connectionAlertView addSubview:alertView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(alertView.frame) + 12, 0, 300, 45)];
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"当前网络不可用，请检查你的网络设置";
        [_connectionAlertView addSubview:label];
        
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showNotConnectWebView:)];
//        tap.numberOfTapsRequired = 1;
//        tap.numberOfTouchesRequired = 1;
//        [_connectionAlertView addGestureRecognizer:tap];
        
    }
    
    return _connectionAlertView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2 ;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChatListMessageCell *cell = [ChatListMessageCell cellForTableView:tableView];
    [cell renderCellWithModel:@{}];

    return cell ;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Chat" bundle:[NSBundle mainBundle]];
    
    ChatInputViewController *inputViewController = [storyboard instantiateViewControllerWithIdentifier:@"chatInputViewController"];
//
//    ChatInputViewController *inputViewController = [ChatInputViewController new] ;
    [self showViewController:inputViewController sender:self];
}

#pragma mark - 左滑显示删除和已读

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChatListMessageCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        BOOL result = [[LLChatManager sharedManager] deleteConversation:cell.conversationModel];
//        if (result) {
//            [self.allConversationModels removeObjectAtIndex:indexPath.row];
//            [tableView deleteRowsAtIndexPaths:@[indexPath]
//                             withRowAnimation:UITableViewRowAnimationFade];
//            [self setUnreadMessageCount];
//        }
    }];
    
    UITableViewRowAction *setReadAction;
//    if (cell.conversationModel.unreadMessageNumber > 0) {
        setReadAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"标为已读" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//            [cell markAllMessageAsRead];
//            [self setUnreadMessageCount];
//            [tableView setEditing:NO animated:YES];
        }];
//    }
    
    return @[deleteAction, setReadAction];
}


- (void)connectionStateChanged:(NSNotification*)notification {
//    BOOL isConnected = [notification.userInfo[@"connectionState"] integerValue] == kLLConnectionStateConnected;
//    
//    if (!isConnected) {
//        self.navigationItem.title = @"微信(未连接)";
        [self.tableHeaderView addSubview:self.connectionAlertView];
//    }else {
//        self.navigationItem.title = @"微信";
//        [self.connectionAlertView removeFromSuperview];
//    }
    
//    [self adjustTableHeaderView];
}

//TableHeaderView 从上至下，依次为SearchBar、connectionAlertView、电脑端登录等
- (void)adjustTableHeaderView {
    CGFloat maxHeight = CGRectGetHeight(self.searchBar.frame);
    if (self.connectionAlertView.superview == _tableHeaderView) {
        self.connectionAlertView.top_LL = maxHeight;
        [self.tableHeaderView addSubview:self.connectionAlertView];
        
        maxHeight = CGRectGetMaxY(self.connectionAlertView.frame);
    }
    
    self.tableHeaderView.height_LL = maxHeight;
    
    [self.tableView setTableHeaderView:self.tableHeaderView];
}


#pragma mark - 搜索 -

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    LLSearchViewController *vc = [LLSearchViewController sharedInstance];
//    LLNavigationController *navigationVC = [[LLNavigationController alloc] initWithRootViewController:vc];
//    navigationVC.view.backgroundColor = [UIColor clearColor];
    vc.delegate = self;
    LLChatSearchController *resultController = [[LLChatSearchController alloc] init];
//    [[LLUtils mainStoryboard] instantiateViewControllerWithIdentifier:SB_CONVERSATION_SEARCH_VC_ID];
    vc.searchResultController = resultController;
    resultController.searchViewController = vc;
    [vc showInViewController:self fromSearchBar:self.searchBar];
    
    return NO;
}

- (void)willPresentSearchController:(LLSearchViewController *)searchController {
    
}

- (void)didPresentSearchController:(LLSearchViewController *)searchController {
    self.tableView.tableHeaderView = nil;
    CGRect frame = _tableHeaderView.frame;
    frame.origin.y = -frame.size.height;
    _tableHeaderView.frame = frame;
}

- (void)willDismissSearchController:(LLSearchViewController *)searchController {
    
    [UIView animateWithDuration:HIDE_ANIMATION_DURATION animations:^{
        _searchBar.hidden = YES;
        self.tableView.tableHeaderView = _tableHeaderView;
    } completion:^(BOOL finished) {
        _searchBar.hidden = NO;
    }];
    
}

- (void)didDismissSearchController:(LLSearchViewController *)searchController {
    //    _connectionAlertView.alpha = 0;
    //    for (UITableViewCell *cell in self.tableView.visibleCells) {
    //        cell.alpha = 0;
    //    }
    //    [UIView animateWithDuration:0.25 animations:^{
    //        _connectionAlertView.alpha = 1;
    //        for (UITableViewCell *cell in self.tableView.visibleCells) {
    //            cell.alpha = 1;
    //        }
    //    }];
}


#pragma mark - 其他 -

//- (void)showNotConnectWebView:(UITapGestureRecognizer *)tap {
//    LLWebViewController *vc = [[LLWebViewController alloc] init];
//    vc.title = @"未能连接到互联网";
//    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"network_setting" ofType:@"html"];
//    vc.url = [NSURL fileURLWithPath:htmlPath];
//    vc.fromViewController = self;
//    
//    [self.navigationController pushViewController:vc animated:YES];
//    
//}


//用户，组。

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
